<template>
  <div class="competition-container">
    <!-- <div class="welcome-header">
      <span>欢迎参加第一届指法大赛！{{ userName }}</span>
    </div> -->
    <div class="competition-header">
      <img src="../assets/cwnu.png" class="competition-logo" alt="logo" />
      <!-- <h1 class="competition-title">正式比赛</h1> -->
    </div>
    <div class="competition-info">
      <span>剩余时间：{{ formattedTime }}</span>
      <span>正确率：{{ accuracy }}%</span>
      <span>正确字符：{{ correctChars }}</span>
    </div>
    <div class="competition-word">
      <span v-if="currentWord" v-html="highlightedWord"></span>
    </div>
    <input
      v-model="userInput"
      @input="onInput"
      @keyup.enter="checkInput"
      :disabled="!currentWord || isGameOver"
      placeholder="请输入上方单词并回车"
      class="competition-input"
    />
    <transition name="fade">
      <div v-if="showPopup" class="competition-popup">
        <a :href="popupWord.url" target="_blank">{{ popupWord.text }}</a>
        <div>{{ popupWord.desc }}</div>
      </div>
    </transition>
    <div v-if="isGameOver" class="game-over-overlay">
      <div class="game-over-popup">
        <div class="popup-header">
          <h2>比赛结束！</h2>
          <img src="../assets/close.png" class="popup-close" @click="onClosePopup" alt="关闭" />
        </div>
        <p>用时：{{ 180 - remainingTime }}秒</p>
        <p>正确率：{{ accuracy }}%</p>
        <p>正确字符：{{ correctChars }}</p>
        <p>速度：{{ typingSpeed }} 字/分钟</p>
        <p>比赛结果已上传，请等待管理员导出</p>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'CompetitionView',
  data () {
    return {
      wordList: [],
      currentIndex: 0,
      userInput: '',
      started: true,
      remainingTime: 180, // 3分钟 = 180秒
      timer: null,
      correctCount: 0, // 正确单词数
      correctChars: 0, // 正确字符数
      totalChars: 0,
      showPopup: false,
      popupWord: {},
      isGameOver: false,
      currentCorrectChars: 0, // 当前单词已输入的正确字符数
      userName: '', // 添加用户名字段
      userId: null, // 添加用户ID字段
      isScoreUploaded: false // 添加成绩上传状态标记
    }
  },
  computed: {
    currentWord () {
      return this.wordList[this.currentIndex] || null
    },
    accuracy () {
      if (this.currentIndex === 0) return 0
      return Math.round((this.correctCount / this.currentIndex) * 100)
    },
    formattedTime () {
      const minutes = Math.floor(this.remainingTime / 60)
      const seconds = this.remainingTime % 60
      return `${minutes}:${seconds.toString().padStart(2, '0')}`
    },
    typingSpeed () {
      // 计算速度（字/分钟）并保留两位小数
      return (this.correctChars / 3).toFixed(2)
    },
    highlightedWord () {
      if (!this.currentWord) return ''
      const target = this.currentWord.text
      const input = this.userInput
      let html = ''
      for (let i = 0; i < target.length; i++) {
        if (i < input.length) {
          if (input[i] === target[i]) {
            html += `<span class='char-correct'>${target[i]}</span>`
          } else {
            html += `<span class='char-wrong'>${target[i]}</span>`
          }
        } else {
          html += `<span class='char-default'>${target[i]}</span>`
        }
      }
      return html
    }
  },
  methods: {
    startTimer () {
      this.stopTimer()
      this.timer = setInterval(() => {
        if (this.remainingTime > 0) {
          this.remainingTime--
        } else {
          this.endGame()
        }
      }, 1000)
    },
    stopTimer () {
      if (this.timer) clearInterval(this.timer)
      this.timer = null
    },
    onInput () {
      if (!this.currentWord || this.isGameOver) return

      const target = this.currentWord.text
      const input = this.userInput
      let correctCount = 0

      // 计算当前输入的正确字符数
      for (let i = 0; i < input.length && i < target.length; i++) {
        if (input[i] === target[i]) {
          correctCount++
        }
      }

      // 更新统计数据
      this.totalChars = Math.max(this.totalChars - this.currentCorrectChars + input.length, 0)
      this.correctChars = Math.max(this.correctChars - this.currentCorrectChars + correctCount, 0)
      this.currentCorrectChars = correctCount
    },
    checkInput () {
      if (!this.currentWord || this.isGameOver) return

      if (this.userInput.trim() === this.currentWord.text) {
        this.correctCount++ // 增加正确单词计数
      }

      this.showWordPopup(this.currentWord)
      this.currentIndex++
      this.currentCorrectChars = 0 // 重置当前单词的正确字符计数
      this.userInput = ''

      if (this.currentIndex >= this.wordList.length) {
        this.endGame()
      }
    },
    showWordPopup (word) {
      this.popupWord = word
      this.showPopup = true
      setTimeout(() => {
        this.showPopup = false
      }, 2000)
    },
    shuffle (arr) {
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[arr[i], arr[j]] = [arr[j], arr[i]]
      }
      return arr
    },
    async endGame () {
      this.stopTimer()
      this.isGameOver = true
      this.started = false

      // 如果成绩还未上传，则上传成绩
      if (!this.isScoreUploaded) {
        try {
          await request.post('/scores', {
            userId: this.userId,
            number: this.correctChars,
            accuracy: this.accuracy / 100 // 将百分比转换为小数
          })
          this.isScoreUploaded = true
          console.log('比赛成绩上传成功')
        } catch (error) {
          console.error('上传成绩失败:', error)
        }
      }

      localStorage.setItem('competitionCompleted', 'true')
    },
    onClosePopup () {
      this.$router.push('/')
    },
    preventNavigation (e) {
      if (!this.isGameOver) {
        e.preventDefault()
        e.returnValue = ''
      }
    }
  },
  async mounted () {
    const module = await import('@/assets/wordlists/Simulation contest.ts')
    this.wordList = this.shuffle([...module.default])
    this.startTimer()

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    this.userName = userInfo.name || ''
    this.userId = userInfo.id // 保存用户ID

    // 添加防止返回的监听器
    window.history.pushState(null, null, window.location.href)
    window.addEventListener('popstate', () => {
      if (!this.isGameOver) {
        window.history.pushState(null, null, window.location.href)
      }
    })

    // 添加页面刷新/关闭提示
    window.addEventListener('beforeunload', this.preventNavigation)
  },
  beforeUnmount () {
    this.stopTimer()
    window.removeEventListener('beforeunload', this.preventNavigation)
  }
}
</script>

<style>
.competition-container {
  max-width: 480px;
  margin: 48px auto 0 auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 32px rgba(0,0,0,0.10);
  padding: 36px 32px 32px 32px;
  text-align: center;
}
.welcome-header {
  background: #42b983;
  color: white;
  padding: 12px 0;
  text-align: center;
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
  letter-spacing: 1px;
}
.competition-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 18px;
}
.competition-logo {
  width: 80px;
  height: 80px;
  margin-bottom: 8px;
}
.competition-title {
  font-size: 2.1rem;
  font-weight: 700;
  color: #2d3a4b;
  letter-spacing: 2px;
  margin-bottom: 0;
}
.competition-info {
  display: flex;
  justify-content: space-between;
  font-size: 1.1rem;
  margin-bottom: 18px;
  color: #444;
}
.competition-word {
  font-size: 2rem;
  font-weight: bold;
  margin: 32px 0 18px 0;
  min-height: 2.5em;
  letter-spacing: 1px;
}
.competition-input {
  width: 100%;
  padding: 10px;
  font-size: 1.2rem;
  border: 2px solid #2ecc40;
  border-radius: 6px;
  outline: none;
  margin-bottom: 18px;
  box-sizing: border-box;
  transition: border 0.2s;
}
.competition-input:focus {
  border-color: #42b983;
}
.competition-popup {
  position: fixed;
  left: 50%;
  bottom: 40px;
  transform: translateX(-50%);
  background: #fff;
  border: 1.5px solid #42b983;
  border-radius: 8px;
  padding: 18px 28px;
  box-shadow: 0 2px 12px rgba(66,185,131,0.13);
  z-index: 1000;
  min-width: 240px;
  text-align: left;
}
.char-correct {
  color: #2ecc40;
}
.char-wrong {
  color: #ff4136;
}
.char-default {
  color: #222;
}
.game-over-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.game-over-popup {
  background: #fff;
  border: 2px solid #42b983;
  border-radius: 12px;
  padding: 24px 32px;
  box-shadow: 0 4px 32px rgba(0,0,0,0.15);
  min-width: 300px;
  text-align: center;
}
.popup-header {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-bottom: 20px;
}
.popup-header h2 {
  color: #2d3a4b;
  margin: 0;
}
.popup-close {
  position: absolute;
  right: -20px;
  top: -10px;
  width: 28px;
  height: 28px;
  cursor: pointer;
  transition: opacity 0.2s;
}
.popup-close:hover {
  opacity: 0.8;
}
.game-over-popup p {
  margin: 8px 0;
  font-size: 1.1rem;
  color: #444;
}
</style>
